package com.xyy.ec.qualification.task;

import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.Uninterruptibles;
import com.xyy.ec.qualification.enums.TaskEnum;
import com.xyy.ec.qualification.pojo.SellerDataConfig;
import com.xyy.ec.qualification.utils.DelayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class TaskExecuteEngine {
    private static final Logger logger = LoggerFactory.getLogger(TaskExecuteEngine.class);
    private ScheduledExecutorService executor = null;
    @Resource(name = SellerDataConfig.strategy)
    private TaskHandler handler;

    @PostConstruct
    private void setup() {
        refresh();
    }

    public synchronized void refresh() {

        if (null != executor) {
            executor.shutdown();
            Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
        }
        if (null != executor && !executor.isShutdown()) {
            executor.shutdownNow();
            Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
        }
        if (null != executor && !executor.isShutdown()) {
            logger.error("refresh_线程池关闭失败");
            return;
        }

        executor = Executors.newScheduledThreadPool(TaskEnum.values().length);

        /**
         * 如果需要设置每天定时几点执行，可以去DelayUtils.getDelay()方法中修改
         */
//        Long delay = DelayUtils.getDelay();

        Long delay = 1L;
        //药检报告
        executor.scheduleWithFixedDelay(() -> {
            try {
                long startTime = System.currentTimeMillis();

                handler.handleDrugReport(TaskEnum.DRUG_REPORT);

                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;

                logger.info("{}任务执行时间,耗时{}ms", JSONObject.toJSONString(TaskEnum.DRUG_REPORT.getTaskName()), duration);

            } catch (Throwable e) {
                logger.error("任务执行失败，error=" + e.getMessage() + ", task=" + JSONObject.toJSONString(TaskEnum.DRUG_REPORT));
                logger.error("scan remote config failed", e);
            }
        }, delay, TaskEnum.DRUG_REPORT.getInterval(), TimeUnit.MINUTES);

        //首营资质
//        executor.scheduleWithFixedDelay(() -> {
//            try {
//                // 任务执行时间
//                long startTime = System.currentTimeMillis();
//
//                handler.handleFirstBattalionQualification(TaskEnum.FIRST_BATTALION_QUALIFICATION);
//
//                long endTime = System.currentTimeMillis();
//                long duration = endTime - startTime;
//
//                logger.info("{}任务执行时间,耗时{}ms", JSONObject.toJSONString(TaskEnum.DRUG_REPORT.getTaskName()), duration);
//
//            } catch (Throwable e) {
//                logger.error("任务执行失败，error=" + e.getMessage() + ", task=" + JSONObject.toJSONString(TaskEnum.FIRST_BATTALION_QUALIFICATION));
//                logger.error("scan remote config failed", e);
//            }
//        }, delay, TaskEnum.FIRST_BATTALION_QUALIFICATION.getInterval(), TimeUnit.MINUTES);

    }

}
